<template>
  <el-dialog :visible.sync="showPointDialog" :before-close="check" title="关联产品" width="70%">
    <div class="app-container">
      <div class="app-head">
        <el-form>
          <el-row type="flex" justify="start">
            <el-col :span="14">
              <el-form-item label="产品ID" label-width="100px">
                <el-input ref="vipHeight" v-model="productId" style="width:90%" size="mini" />
              </el-form-item>
            </el-col>

            <el-col :span="7">
              <el-form-item label="产品名称" label-width="100px">
                <el-input v-model="productName" style="width:90%" size="mini" />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="flexd">
              <el-button size="mini" round type="primary" icon="el-icon-search" @click="loadList">查询</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="14">
              <el-form-item label="开始策略时间" label-width="100px">
                <el-date-picker
                  v-model="beginTime"
                  :picker-options="pickerOptions1"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择开始时间"
                  @change="checkStartTime"
                />至
                <el-date-picker
                  v-model="endTime"
                  :picker-options="pickerOptions2"
                  :editable="false"
                  :style="tiemLen"
                  type="datetime"
                  size="mini"
                  format="yyyy-MM-dd HH:mm:ss"
                  value-format="yyyy-MM-dd HH:mm:ss   "
                  placeholder="选择结束时间"
                  @change="checkTime"
                />
              </el-form-item>
            </el-col>
            <el-col :span="7">
              <el-form-item label="关联服务名称" label-width="100px">
                <el-input v-model="relatedServices" style="width:90%" size="mini" />
              </el-form-item>
            </el-col>
            <el-col :span="2" class="flexd">
              <el-button size="mini" round plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-table">
        <el-table
          ref="multipleTable"
          :data="list"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" :selectable="selectInit" />
          <el-table-column label="产品ID">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.productId"
                :content="scope.row.productId"
                placement="top"
                trigger="hover"
              >
                <span slot="reference" style="cursor:pointer">{{ scope.row.productId }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="产品名称">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.name"
                :content="scope.row.name"
                placement="top"
                trigger="hover"
              >
                <span slot="reference" style="cursor:pointer">{{ scope.row.name }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="关联服务名称">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.serviceName"
                :content="scope.row.serviceName"
                placement="top"
                trigger="hover"
              >
                <span slot="reference" style="cursor:pointer">{{ scope.row.serviceName }}</span>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="产品创建日期">
            <template slot-scope="scope">
              <el-popover
                v-if="scope.row.createTime"
                :content="scope.row.createTime"
                placement="top"
                trigger="hover"
              >
                <span slot="reference" style="cursor:pointer">{{ scope.row.createTime }}</span>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            :current-page="pageid"
            :page-sizes="[20,50,100]"
            :page-size="pagecount"
            :total="count"
            background
            highlight-current-row
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <div class="btnArrs">
          <el-button type="primary" size="small" plain round @click="check">取消</el-button>
          <el-button type="primary" size="small" round @click="connectList">确认关联</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { productExpnse } from '@/api/productGroup.js'
export default {
  props: {
    selectProduct: {
      type: Boolean,
      default: false
    },
    productHas: {
      type: Array,
      default: () => []
    },
    platFormstring: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      list: [],
      platFormstringreal: '',
      middleVal: [],
      count: 0,
      showPointDialog: false,
      tiemLen: '',
      productId: '', // 产品ID
      productName: '', // 产品名称
      relatedServices: '', // 关联服务名称
      beginTime: '', // 开始时间
      endTime: '', // 结束时间
      pageid: 1,
      pagecount: 10,
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      }
    }
  },
  watch: {
    selectProduct(newVal) {
      if (newVal) {
        this.platFormstringreal = this.platFormstring.join(',')
        this.$nextTick(() => {
          var len = this.$refs.vipHeight.$el.offsetWidth / 2 - 10
          this.tiemLen = {
            width: len + 'px'
          }
        })
        this.showPointDialog = newVal
        this.arrPay = this.productHas
        if (this.arrPay.length > 0) {
          this.middleVal = this.arrPay.map((item) => {
            return item.productId
          })
        }
        this.loadList(this.productHas)
        // this.getSelect()
      }
    }
  },
  methods: {
    // 设置选中状态
    toggleSelection() {
      if (this.arrPay) {
        for (let i = 0; i < this.arrPay.length; i++) {
          for (let j = 0; j < this.list.length; j++) {
            if (this.arrPay[i].productId === this.list[j].productId) {
              this.$refs.multipleTable.toggleRowSelection(this.list[j], true)
            }
          }
        }
      }
    },
    connectList() {
      this.middleVal.forEach((item) => {
        this.arr.forEach((num, index) => {
          if (num.productId === item) {
            this.arr.splice(index, 1)
          }
        })
      })
      this.check(this.arr)
    },
    selectInit(row, index) {
      if (this.arrPay.length > 0) {
        var arr = this.arrPay.map((item) => {
          return item.productId
        })
        if (arr.indexOf(row.productId) > -1) {
          return false
        } else {
          return true
        }
      } else {
        return true
      }
    },
    // 多选
    handleSelectionChange(val) {
      if (val.length > 0) {
        this.arr = val
      }
    },
    check(val) {
      this.showPointDialog = false
      this.$emit('closeProduct', val)
      this.reset()
    },
    reset() {
      this.productId = ''
      this.productName = ''
      this.relatedServices = ''
      this.beginTime = ''
      this.endTime = ''
    },
    // 请求列表
    loadList(productHas) {
      this.pageid = 1
      const request = {
        productId: this.productId,
        productName: this.productName,
        relatedServices: this.relatedServices,
        beginTime: this.beginTime,
        platformId: this.platFormstringreal,
        endTime: this.endTime,
        pageid: 1, // 当前页数
        pagecount: 20 // 每页可显示条数 */
      }
      console.log(request)
      productExpnse(request)
        .then((res) => {
          if (res.resultCode === '0000') {
            this.list = res.data.list
            this.count = parseInt(res.data.count) // 总数量
            /* if (this.list.length > 0) {
            this.pageid = parseInt(res.data.list[0].pageid) // 当前页数
          } */
            this.status = true
            this.$nextTick(() => {
              this.toggleSelection()
            })
          }
        })
        .catch(() => {
          this.$message({
            message: '请求列表失败',
            type: 'error'
          })
        })
    },
    // 校验开始时间
    checkStartTime(time) {
      const reg = new RegExp('-', 'g')
      // 比较是否大于现在的时间
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {
            this.beginTime = ''
          }
        })
      } else {
        if (!!time) { // eslint-disable-line
          var end
          if (this.applyEndTime !== null) {
            end = new Date(this.endTime.replace(reg, '/')).getTime()
          } else {
            end = ''
          }
          var first = new Date(time.replace(reg, '/')).getTime()
          if (!!end && first > end) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.beginTime = ''
          }
        }
      }
    },
    // 校验结束时间
    checkTime(time) {
      const reg = new RegExp('-', 'g') // console.log(newStr)
      var selectTime
      if (!!time) { // eslint-disable-line
        selectTime = new Date(time.replace(reg, '/')).getTime() // 所选时间
      } else {
        selectTime = ''
      }
      const nowTime = Date.now() // 现在的时间
      if (selectTime > nowTime) {
        this.$alert('所选时间不能大于当前时间！', '提示', {
          confirmButtonText: '确定',
          callback: (action) => {
            this.endTime = ''
          }
        })
      } else {
        if (!!time) { // eslint-disable-line
          var start
          if (this.startDiscount !== null) {
            start = new Date(this.beginTime.replace(reg, '/')).getTime()
          } else {
            start = ''
          }
          var end = new Date(time.replace(reg, '/')).getTime()
          if (end < start) {
            this.$message({
              message: '开始时间不能大于结束时间',
              type: 'error'
            })
            this.endTime = ''
          }
        }
      }
    },
    // 当前页面显示条数改变时
    handleSizeChange(num) {
      this.flag = false
      const request = {
        productId: this.productId,
        productName: this.productName,
        relatedServices: this.relatedServices,
        beginTime: this.beginTime,
        platformId: this.platFormstringreal,
        endTime: this.endTime,
        pageid: 1, // 当前页数
        pagecount: num // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      productExpnse(request).then((res) => {
        this.list = res.data.list // 列表项
        this.count = parseInt(res.data.count) // 总数量
        this.pageid = 1
        this.pagecount = num
        this.flag = true
      })
    },

    // 跳转某页
    handleCurrentChange(num) {
      console.log(num)
      this.pageid = num // 当前页数
      const request = {
        productId: this.productId,
        productName: this.productName,
        relatedServices: this.relatedServices,
        beginTime: this.beginTime,
        platformId: this.platFormstringreal,
        endTime: this.endTime,
        pageid: num, // 当前页数
        pagecount: this.pagecount // 每页可显示条数
      }
      console.log('请求数据')
      console.log(request)
      // if (this.flag === true) {
      productExpnse(request).then((response) => {
        this.list = response.data.list // 列表项
        this.count = parseInt(response.data.count) // 总数量
        console.log('返回数据')
        console.log(response.data)
      })
      // }
    }
  }
}
</script>

<style scoped>
.addBtns {
  margin: 5px 0;
}
.btnArrs {
  display: flex;
  justify-content: flex-end;
  width: 200px;
  position: absolute;
  right: 0;
  bottom: -58px;
}
.app-table {
  position: relative;
}
</style>
